package com.example.dangerouscargodriver.ui.fragment.resource;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.bean.CityBean;
import com.baiju.bean.ProvinceBean;
import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.baiju.style.multipicker.HashMultiPickerView;
import com.baiju.style.multipicker.MultiPickerView;
import com.baiju.style.multipicker.config.MultiPickerConfig;
import com.baiju.style.multipicker.listener.OnHashMultiPickerItemClickListener;
import com.baiju.style.multipicker.listener.OnMultiPickerItemClickListener;
import com.baiju.style.multipicker.widget.bean.MultiItemBean;
import com.example.dangerouscargodriver.controller.AttrInfoController;
import com.example.dangerouscargodriver.controller.IControllerEventListener;
import com.example.dangerouscargodriver.entry.ResourceInfo;
import com.example.dangerouscargodriver.entry.ResourceSearchInfo;
import com.example.dangerouscargodriver.entry.ResourceTypeInfo2;
import com.example.dangerouscargodriver.entry.TruckClassInfo;
import com.example.dangerouscargodriver.entry.TruckTypeInfo;
import com.example.dangerouscargodriver.event.Event;
import com.example.dangerouscargodriver.event.LoadHttpResourceStatus;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.ui.activity.ProvinceCityDistrictPickerActivity;
import com.example.dangerouscargodriver.ui.fragment.AuthCheckFragment;
import com.example.dangerouscargodriver.ui.fragment.HttpRequestFragment;
import com.example.dangerouscargodriver.ui.fragment.home.HomeFragment;
import com.example.dangerouscargodriver.utils.DisplayUtil;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.widget.BJPullToRefreshScrollView;
import com.example.dangerouscargodriver.widget.LoadingDialog;
import com.example.dangerouscargodriver.widget.RequestMoreResourceInfoView;
import com.example.dangerouscargodriver.widget.ResourceInfoView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.ScrollViewWithListener;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class ResourceFragment extends AuthCheckFragment implements View.OnClickListener {

    private static final String TAG = "ResourceFragment";

    private static final int START_ACTIVITY_FOR_START_CITY = 1;
    private static final int START_ACTIVITY_FOR_END_CITY = 2;

    private static final int MSG_GET_ATTR_CORE = 1;
    private static final int MSG_GET_ATTR_TRUCK_CLASS = 2;

    private static final int CLICK_RESOURCE_TYPE_ITEM = 1;
    private static final int CLICK_WEIGHT_ITEM = 2;
    private static final int CLICK_CAR_TYPE_ITEM = 3;
    private static final int CLICK_TIME_TYPE_ITEM = 4;

    private View mRootView = null;
    private LinearLayout mLayoutContent = null;

    private ArrayList<MultiItemBean> mResTypeArray;
    private MultiPickerView mResourceTypePickerView = null;
    private LinearLayout mResourceTypeLayout = null;
    private LinearLayout mShowResourceTypeLayout = null;
    private List<ResourceTypeInfo2> mResourceTypeArray = null;
    private List<Integer> mResourceTypeSelectArray = null;
    private int mLoadResourceType = 0;

    private ArrayList<MultiItemBean> mWeightArray;
    private MultiPickerView mWeightPickerView = null;
    private LinearLayout mWeightLayout = null;
    private LinearLayout mShowWeightLayout = null;
    private List<Integer> mWeightSelectArray = null;

    private ArrayList<MultiItemBean> mCarTypeArray;
    private HashMultiPickerView mCarTypePickerView = null;
    private LinearLayout mCarTypeLayout = null;
    private LinearLayout mShowCarTypeLayout = null;
    private List<TruckTypeInfo> mTruckTypeArray = null;
    private List<Integer> mSelectTruckCid = null;
    private String mSelectorTruck_cidKey = null;
    private ArrayList<String> mHashKeyArray = null;
    private HashMap<String, ArrayList<MultiItemBean>> mHashMapCarTypeArray = null;
    private int mLoadTruckClass = 0;

    private ArrayList<MultiItemBean> mLoadTimeArray;
    private MultiPickerView mLoadTimePickerView = null;
    private LinearLayout mLoadTimeLayout = null;
    private LinearLayout mShowLoadTimeLayout = null;
    private List<Integer> mLoadTimeSelectArray = null;

    private Button mSearchResource = null;

    private HomeHandler mHandler = null;

    private List<ResourceInfo> mResourceArray = null;
    private int mLoadResource = 0;

    private TextView mStartCity = null;
    private TextView mEndCity = null;
    private CityBean mStartCityBean = null;
    private ProvinceBean mStartProvinceBean = null;
    private CityBean mEndCityBean = null;
    private ProvinceBean mEndProvinceBean = null;

    private ImageView mSwitchView = null;

    private MyControllerEventListener myControllerEventListener = null;

    private BJPullToRefreshScrollView mScrollView = null;
    private RequestMoreResourceInfoView mRequestMore = null;
    private int mSearchResourceInfoNum = 0;
    private int mTotalResourceInfoNum = 0;

    public ResourceFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(ResourceFragment.class);
        super.initAuthCheckComponent(ResourceFragment.class);
        mResTypeArray = new ArrayList<MultiItemBean>();

        mWeightArray = new ArrayList<MultiItemBean>();
        mWeightArray.add(new MultiItemBean("0-10吨","0-10","0"));
        mWeightArray.add(new MultiItemBean("10-20吨","10-20","0"));
        mWeightArray.add(new MultiItemBean("20-32吨","20-32","0"));
        mWeightArray.add(new MultiItemBean("32吨以上","32-32","0"));

        mCarTypeArray = new ArrayList<MultiItemBean>();

        mLoadTimeArray = new ArrayList<MultiItemBean>();
        mLoadTimeArray.add(new MultiItemBean("今天","0","0"));
        mLoadTimeArray.add(new MultiItemBean("明天","1","0"));
        mLoadTimeArray.add(new MultiItemBean("三天内","2","0"));
        mLoadTimeArray.add(new MultiItemBean("一周内","3","0"));
        mLoadTimeArray.add(new MultiItemBean("一周后","4","0"));

        myControllerEventListener = new MyControllerEventListener();

        mResourceArray = new ArrayList<>();
        mResourceTypeSelectArray = new ArrayList<>();
        mWeightSelectArray = new ArrayList<>();
        mSelectTruckCid = new ArrayList<>();
        mLoadTimeSelectArray = new ArrayList<>();

        mHashMapCarTypeArray = new HashMap<>();
        mHashKeyArray = new ArrayList<>();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_resource, container, false);
        mLayoutContent = mRootView.findViewById(R.id.layout_content);
        mRequestMore = new RequestMoreResourceInfoView(getContext());
        mRequestMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                executeSearchAction(false);
            }
        });
        mScrollView = mRootView.findViewById(R.id.layout_scroll_view);

        mResourceTypePickerView = new MultiPickerView();
        mResourceTypePickerView.init(mRootView.getContext(), mResTypeArray);
        mResourceTypeLayout = mRootView.findViewById(R.id.layout_resource_type_select);
        mResourceTypeLayout.setOnClickListener(this);
        mShowResourceTypeLayout = mRootView.findViewById(R.id.layout_resource_type_show);

        mWeightPickerView = new MultiPickerView();
        mWeightPickerView.init(mRootView.getContext(), mWeightArray);
        mWeightLayout = mRootView.findViewById(R.id.layout_weight_select);
        mWeightLayout.setOnClickListener(this);
        mShowWeightLayout = mRootView.findViewById(R.id.layout_weight_show);
        addWeightItem();

        mCarTypePickerView = new HashMultiPickerView();
        mCarTypeLayout = mRootView.findViewById(R.id.layout_car_type_select);
        mCarTypeLayout.setOnClickListener(this);
        mShowCarTypeLayout = mRootView.findViewById(R.id.layout_car_type_show);

        mLoadTimePickerView = new MultiPickerView();
        mLoadTimePickerView.init(mRootView.getContext(), mLoadTimeArray);
        mLoadTimeLayout = mRootView.findViewById(R.id.layout_load_time_select);
        mLoadTimeLayout.setOnClickListener(this);
        mShowLoadTimeLayout = mRootView.findViewById(R.id.layout_load_time_show);
        addLoadTimeItem();

        mSearchResource = mRootView.findViewById(R.id.btn_search_resource);
        mSearchResource.setOnClickListener(this);

        mStartCity = mRootView.findViewById(R.id.tv_start_city);
        mStartCity.setOnClickListener(this);
        mEndCity = mRootView.findViewById(R.id.tv_end_city);
        mEndCity.setOnClickListener(this);

        mSwitchView = mRootView.findViewById(R.id.iv_switch_city);
        mSwitchView.setOnClickListener(this);

        mHandler = new HomeHandler(this);

        AttrInfoController.Instance().attachControllerListener(ResourceFragment.class,
                myControllerEventListener);

        intRefreshScrollView();
        showLoadingDialog();
        executeSearchAction(true);
        return mRootView;
    }

    //进行初使化  （1.设置模式 2.通过getLoadingLayoutProxy方法设置header与footer的刷新显示文字 3.设置监听事件）
    private void intRefreshScrollView() {
        //1.设置模式
        mScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);

        //2.通过调用getLoadingLayoutProxy方法，设置下拉刷新状况布局中显示的文字 ，第一个参数为true,代表下拉刷新
        ILoadingLayout headLables = mScrollView.getLoadingLayoutProxy(true, false);
        headLables.setPullLabel("下拉刷新");
        headLables.setRefreshingLabel("正在刷新");
        headLables.setReleaseLabel("松开刷新");
/*
        //2.设置上拉加载底部视图中显示的文字，第一个参数为false,代表上拉加载更多
        ILoadingLayout footerLables = mScrollView.getLoadingLayoutProxy(false, true);
        footerLables.setPullLabel("上拉加载");
        footerLables.setRefreshingLabel("正在载入...");
        footerLables.setReleaseLabel("松开加载更多");
 */
        //3.设置监听事件
        mScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollViewWithListener>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollViewWithListener> refreshView) {
                //请求网络数据，并更新listview组件
                executeSearchAction(true);
                refreshComplete();//数据加载完成后，关闭header,footer
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollViewWithListener> refreshView) {
                //请求网络数据，并更新listview组件
                refreshComplete();//数据加载完成后，关闭header,footer
            }
        });

    }
    /**
     * 刷新完成时关闭
     */
    public void refreshComplete(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mScrollView.onRefreshComplete();
            }
        },1000);
    }

    @Override
    protected void onLogIn() {

    }

    @Override
    protected void onLogOut() {
        initResourceViewInFragment();
    }

    @Override
    protected void onUserChanged() {
        initResourceViewInFragment();
    }

    @Override
    public void onResume(){
        super.onResume();
    }

    private class MyControllerEventListener implements IControllerEventListener{

        @Override
        public void onEvent(int actionId, String json) {
            if(actionId == Event.EVENT_LOAD_HTTP_RESOURCE_CORE_ATTR){
                Gson gson = new Gson();
                LoadHttpResourceStatus status = gson.fromJson(json, LoadHttpResourceStatus.class);
                Log.d(TAG, "onEvent: " + status.toJson());
                if(status.getWhat() == AttrInfoController.EVENT_ATTR_LOAD_DONE){
                    mResourceTypeArray = AttrInfoController.Instance().getResourceTypeArray();
                    Log.d(TAG, "mResourceTypeArray: " + mResourceTypeArray.toString());
                    mResTypeArray.clear();
                    for(int index = 0; index < mResourceTypeArray.size(); index++){
                        mResTypeArray.add(new MultiItemBean(
                                mResourceTypeArray.get(index).getName1(),
                                Integer.toString(index),
                                "0"));
                    }
                    Message msg = new Message();
                    msg.what = MSG_GET_ATTR_CORE;
                    mHandler.sendMessage(msg);

                    mTruckTypeArray = AttrInfoController.Instance().getTruckTypeArray();
                    mCarTypeArray.clear();
                    if(mTruckTypeArray != null && mTruckTypeArray.size() > 0){
                        for(int index = 0; index < mTruckTypeArray.size(); index++){
                            TruckTypeInfo truckTypeInfo = mTruckTypeArray.get(index);
                            List<TruckClassInfo> list = truckTypeInfo.getList();
                            ArrayList<MultiItemBean> arrayList = new ArrayList<>();
                            for(int index2 = 0; index2 < list.size(); index2++) {
                                MultiItemBean bean = new MultiItemBean();
                                bean.setName(list.get(index2).getClassname());
                                bean.setId(list.get(index2).getClassid());
                                bean.setSelected("0");
                                arrayList.add(bean);
                                mCarTypeArray.add(bean);
                            }
                            mHashMapCarTypeArray.put(truckTypeInfo.getType(), arrayList);
                            mHashKeyArray.add(truckTypeInfo.getType());
                        }
                    }
                    mCarTypePickerView.init(mRootView.getContext(), mHashMapCarTypeArray, mHashKeyArray);
                    Message msg2 = new Message();
                    msg2.what = MSG_GET_ATTR_TRUCK_CLASS;
                    mHandler.sendMessage(msg2);
                }
            }
            else{
                /**/
            }
        }
    }

    @Override
    public void onClick(@NotNull View v) {
        if(v.getId() == R.id.layout_resource_type_select){
            if(mResTypeArray.size() <= 0){
                return;
            }
            MultiPickerConfig pickerConfig = new MultiPickerConfig.Builder()
                    .title("选择类别")
                    .build();

            mResourceTypePickerView.setConfig(pickerConfig);
            mResourceTypePickerView.setOnMultiItemClickListener(new OnMultiPickerItemClickListener() {
                public void onSelected(List<Integer> select) {
                    if(select.size() > 0) {
                        mResourceTypeSelectArray = select;
                        addResourceTypeItem(select);
                    }
                    else if(select.size() == 0){
                        addResourceTypeItem();
                    }
                    else{
                        /**/
                    }
                }

                @Override
                public void onCancel() {
                    /**/
                }
            });

            mResourceTypePickerView.showMultiPicker();
        }
        else if(v.getId() == R.id.layout_weight_select){
            MultiPickerConfig pickerConfig = new MultiPickerConfig.Builder()
                    .title("选择重量")
                    .build();

            mWeightPickerView.setConfig(pickerConfig);
            mWeightPickerView.setOnMultiItemClickListener(new OnMultiPickerItemClickListener() {
                @Override
                public void onSelected(List<Integer> select) {
                    if(select.size() > 0) {
                        mWeightSelectArray = select;
                        addWeightItem(select);
                    }
                    else if(select.size() == 0){
                        addWeightItem();
                    }
                    else{
                        /**/
                    }
                }

                @Override
                public void onCancel() {
                    /**/
                }
            });

            mWeightPickerView.showMultiPicker();
        }
        else if(v.getId() == R.id.layout_car_type_select){
            if(mHashMapCarTypeArray.size() <= 0){
                return;
            }

            MultiPickerConfig pickerConfig = new MultiPickerConfig.Builder()
                    .title("选择车型")
                    .build();

            mCarTypePickerView.setConfig(pickerConfig);
            mCarTypePickerView.setOnMultiItemClickListener(new OnHashMultiPickerItemClickListener() {
                public void onSelected(String selectKey, List<Integer> select) {
                    mSelectTruckCid = select;
                    mSelectorTruck_cidKey = selectKey;
                    if(select.size() > 0) {
                        addCarTypeItem(selectKey, select);
                    }
                    else if(select.size() == 0){
                        addCarTypeItem();
                    }
                    else{
                        /**/
                    }
                }

                @Override
                public void onCancel() {
                    /**/
                }
            });

            mCarTypePickerView.showHashMultiPicker();
        }
        else if(v.getId() == R.id.layout_load_time_select){
            MultiPickerConfig pickerConfig = new MultiPickerConfig.Builder()
                    .title("选择时间")
                    .couldSelectNum(1)
                    .build();

            mLoadTimePickerView.setConfig(pickerConfig);
            mLoadTimePickerView.setOnMultiItemClickListener(new OnMultiPickerItemClickListener() {
                @Override
                public void onSelected(List<Integer> select) {
                    /**/
                    if(select.size() > 0) {
                        mLoadTimeSelectArray = select;
                        addLoadTimeItem(select);
                    }
                    else if(select.size() == 0){
                        addLoadTimeItem();
                    }
                    else{
                        /**/
                    }
                }

                @Override
                public void onCancel() {
                    /**/
                }
            });

            mLoadTimePickerView.showMultiPicker();
        }
        else if(v.getId() == R.id.tv_start_city){
            Intent intent = new Intent(ResourceFragment.this.getActivity(), ProvinceCityDistrictPickerActivity.class);
            intent.putExtra("type", ProvinceCityDistrictPickerActivity.AREA_SELECT_CITY_WITH_ALL_PROVINCE);
            intent.putExtra("province", mStartProvinceBean);
            intent.putExtra("city", mStartCityBean);
            startActivityForResult(intent, START_ACTIVITY_FOR_START_CITY);
        }
        else if(v.getId() == R.id.tv_end_city){
            Intent intent = new Intent(ResourceFragment.this.getActivity(), ProvinceCityDistrictPickerActivity.class);
            intent.putExtra("type", ProvinceCityDistrictPickerActivity.AREA_SELECT_CITY_WITH_ALL_PROVINCE);
            intent.putExtra("province", mEndProvinceBean);
            intent.putExtra("city", mEndCityBean);
            startActivityForResult(intent, START_ACTIVITY_FOR_END_CITY);
        }
        else if(v.getId() == R.id.iv_switch_city){
            if(mStartCityBean == null || mEndCityBean == null){
                return;
            }
            CityBean tmpCity = mStartCityBean;
            ProvinceBean tmpProvince = mStartProvinceBean;
            mStartCityBean = mEndCityBean;
            mStartProvinceBean = mEndProvinceBean;
            mEndCityBean = tmpCity;
            mEndProvinceBean = tmpProvince;
            if (mStartCityBean != null) {
                mStartCity.setText(mStartCityBean.getId().equals("0") ?
                        mStartProvinceBean.getName() : mStartCityBean.getName());
            }
            mEndCity.setText(mEndCityBean.getName());
            if (mEndCityBean != null) {
                mEndCity.setText(mEndCityBean.getId().equals("0") ?
                        mEndProvinceBean.getName() : mEndCityBean.getName());
            }
        }
        else if(v.getId() == R.id.btn_search_resource){
            Log.d(TAG, "mCarTypeSelectArray: " + mSelectTruckCid.toString());
            Log.d(TAG, "mWeightSelectArray: " + mWeightSelectArray.toString());
            Log.d(TAG, "mLoadTimeSelectArray: " + mLoadTimeSelectArray.toString());
            Log.d(TAG, "mResourceTypeSelectArray: " + mResourceTypeSelectArray.toString());

            mResourceArray.clear();
            mLayoutContent.removeAllViews();
            executeSearchAction(true);
        }
        else{

        }
    }

    private void addCarTypeItem(String selectKey, List<Integer> select) {
        if(select == null){
            return;
        }

        mShowCarTypeLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);

            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(mRootView.getContext(), 12),
                    0,
                    0,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mHashMapCarTypeArray.get(selectKey).get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            mShowCarTypeLayout.addView(itemLayout);
        }
    }

    private void executeSearchAction(boolean refresh) {
        HashMap<String, String> param = new HashMap<String, String>();
        if(mSelectTruckCid.size() > 0){
            String truck_cid = "";
            for(int index = 0; index < mSelectTruckCid.size(); index++){
                truck_cid += mHashMapCarTypeArray.get(mSelectorTruck_cidKey).get(index).getId();
                truck_cid += ",";
            }
            truck_cid = truck_cid.substring(0, truck_cid.length() - 1);
            param.put("truck_cid", truck_cid);
        }
        if(mLoadTimeSelectArray.size() > 0){
            String loadtime = "";
            for(int index = 0; index < mLoadTimeSelectArray.size(); index++){
                loadtime += mLoadTimeArray.get(mLoadTimeSelectArray.get(index)).getName();
                loadtime += ",";
            }
            loadtime = loadtime.substring(0, loadtime.length() - 1);
            param.put("loadtime", loadtime);
        }
        if(mWeightSelectArray.size() > 0){
            String weight = "";
            for(int index = 0; index < mWeightSelectArray.size(); index++){
                weight += mWeightArray.get(mWeightSelectArray.get(index)).getId();
                weight += ",";
            }
            weight = weight.substring(0, weight.length() - 1);
            param.put("weight", weight);
        }
        if(mResourceTypeSelectArray.size() > 0){
            String resourceType = "";
            for(int index = 0; index < mResourceTypeSelectArray.size(); index++){
                resourceType += mResourceTypeArray.get(mResourceTypeSelectArray.get(index)).getId();
                resourceType += ",";
            }
            resourceType = resourceType.substring(0, resourceType.length() - 1);
            param.put("class_id", resourceType);
        }

        if(refresh) {
            mTotalResourceInfoNum = 0;
            mSearchResourceInfoNum = 0;
            mResourceArray.clear();
            param.put("page", Integer.toString(mSearchResourceInfoNum / 10 + 1));
            sendHttpRequest(
                    IHttpRequest.RequestMethod.GET_METHOD,
                    RemoteAPI.REQUEST_V1_HOME_SEARCH_SOURCE_GOODS,
                    null,
                    param,
                    RemoteAPICmd.REQUEST_V1_HOME_SEARCH_SOURCE_GOODS);
        }
        else{
            if(mSearchResourceInfoNum >= mTotalResourceInfoNum){
                ToastUtils.showLongToast(getContext(), "已无更多数据");
            }
            else {
                param.put("page", Integer.toString(mSearchResourceInfoNum / 10 + 1));
                sendHttpRequest(
                        IHttpRequest.RequestMethod.GET_METHOD,
                        RemoteAPI.REQUEST_V1_HOME_SEARCH_SOURCE_GOODS,
                        null,
                        param,
                        RemoteAPICmd.REQUEST_V1_HOME_SEARCH_SOURCE_GOODS_PAGE);
            }
        }
    }

    private void initResourceViewInFragment() {
        if(mResourceArray != null) {
            mLayoutContent.removeAllViews();
            for(int index = 0; index < mResourceArray.size(); index++) {
                final int click = index;
                ResourceInfoView view = new ResourceInfoView(mRootView.getContext(),
                        mResourceArray.get(index));
                view.bindData(mResourceArray.get(index));
                mLayoutContent.addView(view);
            }

            mLayoutContent.addView(mRequestMore);
        }
    }

    private static class HomeHandler extends Handler {
        private String TAG = "HomeHandler";
        private final WeakReference<ResourceFragment> mActivity;

        HomeHandler(ResourceFragment activity) {
            mActivity = new WeakReference<ResourceFragment>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ResourceFragment activity = mActivity.get();
            switch (msg.what){
                case MSG_GET_ATTR_CORE:
                    activity.addResourceTypeItem();
                    break;
                case MSG_GET_ATTR_TRUCK_CLASS:
                    activity.addCarTypeItem();
                    break;
                default:
                    break;
            }
        }
    }

    private void addLoadTimeItem() {
        mShowLoadTimeLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getContext());
        for(int index = 0; index < mLoadTimeArray.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(mRootView.getContext(), 12),
                    0,
                    0,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mLoadTimeArray.get(index).getName());
            if(mLoadTimeArray.get(index).getSelected().equals("1")){
                itemLayout.setBackgroundResource(R.drawable.rounded_button);
            }
            itemLayout.setOnClickListener(new ChooseItemListener(index, CLICK_TIME_TYPE_ITEM, ResourceFragment.this));
            mShowLoadTimeLayout.addView(itemLayout);
        }
    }

    private void addLoadTimeItem(List<Integer> select) {
        if(select == null){
            return;
        }

        mShowLoadTimeLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(mRootView.getContext(), 12),
                    0,
                    0,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mLoadTimeArray.get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            itemLayout.setOnClickListener(new ChooseItemListener(select.get(index),
                    CLICK_RESOURCE_TYPE_ITEM,
                    ResourceFragment.this));
            mShowLoadTimeLayout.addView(itemLayout);
        }
    }

    private void addWeightItem() {
        mShowWeightLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getContext());
        for(int index = 0; index < mWeightArray.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(mRootView.getContext(), 12),
                    0,
                    0,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mWeightArray.get(index).getName());
            itemLayout.setOnClickListener(new ChooseItemListener(index,
                    CLICK_WEIGHT_ITEM,
                    ResourceFragment.this));
            mShowWeightLayout.addView(itemLayout);
        }
    }

    private void addWeightItem(List<Integer> select) {
        if(select == null){
            return;
        }

        mShowWeightLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(mRootView.getContext(), 12),
                    0,
                    0,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mWeightArray.get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            itemLayout.setOnClickListener(new ChooseItemListener(select.get(index),
                    CLICK_RESOURCE_TYPE_ITEM,
                    ResourceFragment.this));
            mShowWeightLayout.addView(itemLayout);
        }
    }

    private void addResourceTypeItem() {
        mShowResourceTypeLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getContext());
        for(int index = 0; index < mResTypeArray.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(mRootView.getContext(), 12),
                    0,
                    0,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mResTypeArray.get(index).getName());
            itemLayout.setOnClickListener(new ChooseItemListener(index,
                    CLICK_RESOURCE_TYPE_ITEM,
                    ResourceFragment.this));
            mShowResourceTypeLayout.addView(itemLayout);
        }
    }

    private void addResourceTypeItem(List<Integer> select) {
        if(select == null){
            return;
        }

        mShowResourceTypeLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(mRootView.getContext(), 12),
                    0,
                    0,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mResTypeArray.get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            itemLayout.setOnClickListener(new ChooseItemListener(select.get(index),
                    CLICK_RESOURCE_TYPE_ITEM,
                    ResourceFragment.this));
            mShowResourceTypeLayout.addView(itemLayout);
        }
    }

    private void addCarTypeItem() {
        mShowCarTypeLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getContext());
        for(int index = 0; index < mCarTypeArray.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(mRootView.getContext(), 12),
                    0,
                    0,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mCarTypeArray.get(index).getName());
            itemLayout.setOnClickListener(new ChooseItemListener(index,
                    CLICK_CAR_TYPE_ITEM,
                    ResourceFragment.this));
            mShowCarTypeLayout.addView(itemLayout);
        }
    }

    private void addCarTypeItem(List<Integer> select) {
        if(select == null){
            return;
        }

        mShowCarTypeLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(mRootView.getContext(), 12),
                    0,
                    0,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mCarTypeArray.get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            itemLayout.setOnClickListener(new ChooseItemListener(select.get(index),
                    CLICK_CAR_TYPE_ITEM,
                    ResourceFragment.this));
            mShowCarTypeLayout.addView(itemLayout);
        }
    }

    @Override
    public void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();

            if(actionId == RemoteAPICmd.REQUEST_V1_HOME_SEARCH_SOURCE_GOODS){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    JSONObject data = res.getJSONObject("data");
                    ResourceSearchInfo searchInfo = gson.fromJson(data.toString(), ResourceSearchInfo.class);
                    mTotalResourceInfoNum = searchInfo.getCount();
                    if(mResourceArray.size() < searchInfo.getCount()){
                        mSearchResourceInfoNum += searchInfo.getSource_goods().size();
                        for(int index = 0; index < searchInfo.getSource_goods().size(); index++){
                            mResourceArray.add(searchInfo.getSource_goods().get(index));
                        }

                        initResourceViewInFragment();
                    }
                }
                dismissLoadingDialog();
            }
            if(actionId == RemoteAPICmd.REQUEST_V1_HOME_SEARCH_SOURCE_GOODS_PAGE){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    JSONObject data = res.getJSONObject("data");
                    ResourceSearchInfo searchInfo = gson.fromJson(data.toString(), ResourceSearchInfo.class);
                    if(mResourceArray.size() < searchInfo.getCount()){
                        mSearchResourceInfoNum += searchInfo.getSource_goods().size();
                        for(int index = 0; index < searchInfo.getSource_goods().size(); index++){
                            mResourceArray.add(searchInfo.getSource_goods().get(index));
                        }

                        initResourceViewInFragment();
                    }
                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V1_HOME_SEARCH_SOURCE_GOODS){
            dismissLoadingDialog();
        }
        else if(actionId == RemoteAPICmd.REQUEST_V1_HOME_SEARCH_SOURCE_GOODS_PAGE){
        }
    }

    private class ChooseItemListener implements View.OnClickListener{

        private int mSelect = 0;
        private int mType = 0;
        private final WeakReference<ResourceFragment> mFragment;

        public ChooseItemListener(int select, int type, ResourceFragment fragment){
            mSelect = select;
            mType = type;
            mFragment = new WeakReference<ResourceFragment>(fragment);
        }

        @Override
        public void onClick(View v) {
            if(mFragment.get()!= null){
                if(mType == CLICK_RESOURCE_TYPE_ITEM){
                    String select = mResTypeArray.get(mSelect).getSelected();
                    if(select.equals("0")){
                        mFragment.get().mResTypeArray.get(mSelect).setSelected("1");
                        v.setBackgroundResource(R.drawable.rounded_button);
                        if(mResourceTypeSelectArray != null) {
                            mResourceTypeSelectArray.add(mSelect);
                        }
                    }else if(select.equals("1")){
                        mFragment.get().mResTypeArray.get(mSelect).setSelected("0");
                        v.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                        if(mResourceTypeSelectArray != null) {
                            for (int index = 0; index < mResourceTypeSelectArray.size(); index++) {
                                if(mResourceTypeSelectArray.get(index) == mSelect){
                                    mResourceTypeSelectArray.remove(index);
                                    break;
                                }
                            }
                        }
                    }
                    else{

                    }
                }
                else if(mType == CLICK_CAR_TYPE_ITEM){
                    String select = mCarTypeArray.get(mSelect).getSelected();
                    if(select.equals("0")){
                        mFragment.get().mCarTypeArray.get(mSelect).setSelected("1");
                        v.setBackgroundResource(R.drawable.rounded_button);
                        if(mSelectTruckCid != null) {
                            mSelectTruckCid.add(mSelect);
                        }
                        else{

                        }
                    }
                    else if(select.equals("1")){
                        mFragment.get().mCarTypeArray.get(mSelect).setSelected("0");
                        v.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                        if(mSelectTruckCid != null) {
                            for (int index = 0; index < mSelectTruckCid.size(); index++) {
                                if(mSelectTruckCid.get(index) == mSelect){
                                    mSelectTruckCid.remove(index);
                                    break;
                                }
                            }
                        }
                    }
                    else{

                    }
                }
                else if(mType == CLICK_WEIGHT_ITEM){
                    String select = mWeightArray.get(mSelect).getSelected();
                    if(select.equals("0")){
                        mFragment.get().mWeightArray.get(mSelect).setSelected("1");
                        v.setBackgroundResource(R.drawable.rounded_button);
                        if(mWeightSelectArray != null) {
                            mWeightSelectArray.add(mSelect);
                        }
                        else{

                        }
                    }
                    else if(select.equals("1")){
                        mFragment.get().mWeightArray.get(mSelect).setSelected("0");
                        v.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                        if(mWeightSelectArray != null) {
                            for (int index = 0; index < mWeightSelectArray.size(); index++) {
                                if(mWeightSelectArray.get(index) == mSelect){
                                    mWeightSelectArray.remove(index);
                                    break;
                                }
                            }
                        }
                    }
                    else{

                    }
                }
                else if(mType == CLICK_TIME_TYPE_ITEM){
                    String select = mLoadTimeArray.get(mSelect).getSelected();
                    if(select.equals("0")){
                        for(int index = 0; index < mFragment.get().mLoadTimeArray.size(); index++) {
                            if(index == mSelect) {
                                mFragment.get().mLoadTimeArray.get(index).setSelected("1");
                                if (mLoadTimeSelectArray != null) {
                                    mLoadTimeSelectArray.clear();
                                    mLoadTimeSelectArray.add(mSelect);
                                } else {

                                }
                            }
                            else{
                                mFragment.get().mLoadTimeArray.get(index).setSelected("0");
                            }
                        }
                        addLoadTimeItem();
                    }
                    else if(select.equals("1")){
                        mFragment.get().mLoadTimeArray.get(mSelect).setSelected("0");
                        if(mLoadTimeSelectArray != null) {
                            mLoadTimeSelectArray.clear();
                        }
                        addLoadTimeItem();
                    }
                    else{

                    }
                }
                else{
                    /**/
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == START_ACTIVITY_FOR_START_CITY){
            if(data != null) {
                mStartCityBean = (CityBean) data.getParcelableExtra("city");
                mStartProvinceBean = (ProvinceBean) data.getParcelableExtra("province");
                if (mStartCityBean != null) {
                    mStartCity.setText(mStartCityBean.getId().equals("0") ?
                            mStartProvinceBean.getName() : mStartCityBean.getName());
                }
            }
        }
        else if(requestCode == START_ACTIVITY_FOR_END_CITY){
            if(data != null) {
                mEndCityBean = (CityBean) data.getParcelableExtra("city");
                mEndProvinceBean = (ProvinceBean) data.getParcelableExtra("province");
                if (mEndCityBean != null) {
                    mEndCity.setText(mEndCityBean.getId().equals("0") ?
                            mEndProvinceBean.getName() : mEndCityBean.getName());
                }
            }
        }
        else{

        }
    }
}